package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemakerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojo.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.avro.data.Json;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2022/1/26 17:34
 */

@Service
public class ArticleFreemakerServiceImpl implements ArticleFreemakerService {


    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;

    @Override
    public void buildArticleToMinio(ApArticle apArticle, String content) {

        // 已知文章id
        // 获取文章类容
        if (StringUtils.isNotBlank(content)) {
            StringWriter out = null;
            try {
                // 文章通过freemarker生成html文件
                Template template = null;
                 out = new StringWriter();
                template = configuration.getTemplate("article.ftl");
                // 将数据模型添加到集合中
                Map<String, Object> contentDataModel = new HashMap<>();
                contentDataModel.put("content", JSONArray.parseArray(content));
                // 合成
                template.process(contentDataModel, out);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes());
            // 把html文件上传到minio中
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);
            // 修改ap_article表， 保存static_url字段
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId, apArticle.getId()).set(ApArticle::getStaticUrl, path));
        }

    }
}
